package com.jeff.android.lab.database.ormlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
import com.jeff.android.lab.database.ormlite.model.UserInfo;

import java.sql.SQLException;


public class DataBaseHelper extends OrmLiteSqliteOpenHelper {

    private final static String DB_NAME = "demo.db";
    private final static int DB_VERSION = 1;

    private static DataBaseHelper instance;

    public static synchronized DataBaseHelper getDatabaseHelper(Context context) {
        if (instance == null) {
            synchronized (DataBaseHelper.class) {
                if (instance == null) {
                    instance = new DataBaseHelper(context);
                }
            }
        }
        return instance;
    }

    public DataBaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) {
        try {
            TableUtils.createTableIfNotExists(connectionSource, UserInfo.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) {

    }

    private Dao<UserInfo, ?> mUserDao;

    public Dao<UserInfo, ?> getUserDao() throws SQLException {
        if (mUserDao == null)
            mUserDao = getDao(UserInfo.class);
        return mUserDao;
    }

}
